<!--
 @description：点餐界面
 @author: Xg
 @date: 2021/7/1 14:50
-->
<template>
  <!-- 点餐页面 -->
  <div>
    <el-dialog
      :title="title + ' - ' + storeInfo.storeName"
      :visible="orderMainVisible"
      append-to-body
      width="100%"
      class="dialogClass"
      :fullscreen="fullscreen"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="closeDialog(true)"
    >
      <div class="main">
        <el-row class="main">
          <!-- 搜索栏，菜品信息 -->
          <el-col :span="19" class="center">
            <!-- 搜索栏 -->
            <div class="center-top">
              <!-- @input="pageList" 边输入便搜索，加上这个用起来很爽，但是会一直发送请求 -->
              <el-input v-model="foodParams.foodName" placeholder="搜索菜品..." class="search-input" clearable @keydown.enter.native="pageList" />
              <el-button type="primary" icon="el-icon-search" @click="pageList">搜索</el-button>
            </div>
            <!-- 菜品信息 -->
            <!--            <div class="center-bottom">-->
            <!--              <el-row>-->
            <!--                <el-col v-for="(item,index) in foods" :key="index" style="margin: 5px;width: 240px;">-->
            <!--                  <div class="food-info" style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);padding: 5px">-->
            <!--                    <b style="font-size: 18px;color: #666666">{{ item.foodName }}</b>-->
            <!--                    <p>-->
            <!--                      ￥<span style="color: red;font-size: 20px;font-weight: bold">{{ item.price.toFixed(2) }}</span><span style="font-size: 11px;color: #5a5e66">&nbsp;&nbsp;&nbsp;累计点过<span style="color: #CE5639;font-size: 15px">{{ item.count }}</span>单</span>-->
            <!--                    </p>-->
            <!--                    <el-row>-->
            <!--                      <el-col :span="11">-->
            <!--                        <el-rate-->
            <!--                          v-model="item.spicy"-->
            <!--                          :max="3"-->
            <!--                          :low-threshold="lowThreshold"-->
            <!--                          :texts="texts"-->
            <!--                          show-text-->
            <!--                          :icon-classes="iconClasses"-->
            <!--                          :colors="['black','red','red']"-->
            <!--                          disabled-void-icon-class="iconfont icon-lajiao"-->
            <!--                          disabled-->
            <!--                        />-->
            <!--                      </el-col>-->
            <!--                      <el-col :span="13">-->
            <!--                        <el-link type="primary" icon="el-icon-dish" @click="openFoodInfoDialog(item.foodId)">详情</el-link>-->
            <!--                        <el-link v-if="!item.isPress" type="primary" icon="el-icon-circle-plus-outline" @click="selectFood(item)">添加</el-link>-->
            <!--                        <span v-if="item.isPress" class="input-number-component">-->
            <!--                          <i class="el-icon-minus" @click="deleteFood(item)" />-->
            <!--                          &nbsp;-->
            <!--                          <span class="input-number">{{ item.shoppingNumber }}</span>-->
            <!--                           &nbsp;-->
            <!--                          <i class="el-icon-plus" @click="selectFood(item)" />-->
            <!--                        </span>-->
            <!--                      </el-col>-->
            <!--                    </el-row>-->

            <!--                  </div>-->
            <!--                </el-col>-->
            <!--              </el-row>-->
            <!--            </div>-->

            <div class="center-bottom">
              <el-row>
                <el-col v-for="(item,index) in foods" :key="index" style="margin: 5px;width: 240px;">
                  <div id="food" class="food-info">
                    <b id="el-foodName" class="el-food-name">{{ item.foodName }}</b>
                    <p>
                      <el-rate
                        v-model="item.spicy"
                        :max="3"
                        :low-threshold="lowThreshold"
                        :texts="texts"
                        show-text
                        :icon-classes="iconClasses"
                        :colors="['black','red','red']"
                        disabled-void-icon-class="iconfont icon-lajiao"
                        disabled
                      />
                    </p>
                    <p id="el-foodPriceCount">
                      ￥<span id="el-foodPrice" class="el-food-price">{{ item.price.toFixed(2) }}</span>
                      <span id="el-foodCount" class="el-food-count">&nbsp;&nbsp;&nbsp;累计点过<span id="foodCount" class="food-count">{{ item.count }}</span>单</span>
                    </p>
                    <p>
                      <el-link type="primary" icon="el-icon-dish" @click="openFoodInfoDialog(item.foodId)">详情</el-link>
                      &nbsp;
                      <el-link v-if="!item.isPress" type="primary" icon="el-icon-circle-plus-outline" @click="selectFood(item)">添加</el-link>
                      <span v-if="item.isPress" class="input-number-component">
                        <i class="el-icon-minus" @click="deleteFood(item)" />
                           &nbsp;
                        <span class="input-number">{{ item.shoppingNumber }}</span>
                           &nbsp;
                        <i class="el-icon-plus" @click="selectFood(item)" />
                      </span>
                    </p>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-col>
          <!-- 已点列表 -->
          <el-col :span="5" class="right">
            <div class="r1" style="height: 100%">
              <!-- 标题 -->
              <div class="right-top" align="center">
                <div class="shop-title">已点列表</div>
              </div>
              <!-- 购物车 -->
              <div class="right-center">
                <el-col v-for="(item,index) in shoppingCartData" :key="index" :span="4" :offset="0" class="card-panel-col-shopping">
                  <div :body-style="{ padding: '0px 0px' }">
                    <div class="card-title">
                      <div class="right-format">
                        <div style="height: 20px">
                          <el-col :span="16">
                            <span class="title-span">{{ item.foodName }}</span>
                          </el-col>
                          <el-col :span="8" align="right">
                            <span class="input-number-component-shopping">
                              <i class="el-icon-minus" @click="deleteFoodInShopping(item)" />
                              &nbsp;
                              <span class="input-number">{{ item.number }}</span>
                              &nbsp;
                              <i class="el-icon-plus" @click="selectFoodInShopping(item)" />
                            </span>
                          </el-col>
                        </div>
                        <div class="middle">
                          <p>
                            <el-col :span="10" class="shopping-price">￥{{ (item.singlePrice * item.number).toFixed(2) }}</el-col>
                            <el-col :span="14" class="shop-button">
                              <!--                              <el-input v-model="item.foodRemark" size="mini" style="width: 100%" placeholder="请输入备注（非必填）" maxlength="15" show-word-limit @input="onInput()" />-->
                            </el-col>
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-col>
              </div>
              <!-- 下单确认 -->
              <div class="right-bottom">
                <el-form align="right">
                  <!-- 已点列表中加减的时候，会出现-0.00的情况，但不影响正常使用，所以在前端做一下显示处理 -->
                  <div>
                    总价：<span style="color: red;font-size: 25px">{{ totalPrice === 0 ? '0.00' : totalPrice.toFixed(2).replace('-', '') }}</span>元
                    &nbsp;&nbsp;&nbsp;
                    共<span style="color: red;font-size: 25px">{{ numberSum }}</span>样菜品
                  </div>
                  <el-button v-if="hasShoppingData" type="success" size="large" @click="confirmOrder()">保存</el-button>
                  <el-button v-if="hasShoppingData" type="danger" size="large" @click="resetFood()">清空</el-button>
                </el-form>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <food-info
      v-if="foodInfoVisible"
      :food-info-visible="foodInfoVisible"
      :food-id="foodId"
      @close="closeFoodInfoDialog"
    />

  </div>
</template>

<script>
import { list } from '@/api/basic/food'
import { resetFood, getShoppingCartData, saveShoppingCart } from '@/api/meal/shoppingCart'
import { saveOrder } from '@/api/meal/order'
import { getStoreInfo } from '@/api/meal/task'
import FoodInfo from './foodInfo'

export default {
  name: 'OrderMain',
  components: { FoodInfo },
  props: {
    orderMainVisible: {
      type: Boolean,
      default: false
    },
    taskId: {
      type: String,
      default: null
    }
  },
  component: {
    FoodInfo
  },
  data() {
    return {
      remarkTitle: null,
      storeInfo: {},
      title: '欢迎点餐',
      remarkFormVisible: false,
      foodInfoVisible: false,
      foodData: null,
      // remarkData: {
      //   foodId: null,
      //   foodRemark: null
      // },
      lowThreshold: 1,
      texts: ['不辣', '微辣', '重辣'],
      iconClasses: ['iconfont icon-lajiao', 'iconfont icon-lajiao', 'iconfont icon-lajiao'],
      // 商家信息
      foodId: null,
      stores: [],
      foods: [],
      foodParams: {
        foodName: null,
        storeId: null,
        pageSize: 50,
        pageIndex: 1
      },
      active: null,
      // 已点列表数据
      shoppingCartData: [],
      // 下单待提交的数据
      shopData: [],
      // 操作备注框id
      shoppingCartId: null,
      // 菜品计数
      numberSum: 0,
      // 购物车总价
      totalPrice: 0,
      fullscreen: true,
      // 已点列表存在数据时，才显示保存和清空按钮
      hasShoppingData: false
    }
  },
  created() {
    // 获取菜品列表
    this.initStoreAndFood()
  },
  mounted() {
    // 回显购物车信息
    // this.getShoppingCartData()
  },
  methods: {
    // 强制刷新(备注框 组件嵌套太深，没有这个方法的话输入不了)
    onInput() {
      this.$forceUpdate()
    },
    // 关闭菜品详情页面
    closeFoodInfoDialog() {
      this.foodId = null
      this.foodInfoVisible = false
    },
    // 打开菜品详情页面
    openFoodInfoDialog(foodId) {
      this.foodId = foodId
      this.foodInfoVisible = true
    },
    // 回显的购物车信息
    getShoppingCartData() {
      getShoppingCartData({ taskId: this.taskId }).then(res => {
        const that = this
        if (res.code === 200) {
          this.shoppingCartData = res.data.data
          // 循环重新展示，并添加到待提交数据中
          this.foods.forEach(function(foodField) {
            that.shoppingCartData.forEach(function(shoppingField) {
              if (foodField.foodId === shoppingField.foodId) {
                // 如果有在购物车出现，肯定是被选中的
                foodField.shoppingNumber = shoppingField.number
                foodField.isPress = true
              }
            })
          })
          this.shoppingCartData.forEach(function(list) {
            // that.foods.forEach(function(foodList) {
            //   if (list.foodId === foodList.foodId) {
            //     foodList.isPress = true
            //     foodList.shoppingNumber = list.number
            //   }
            // })
            // 处理图片
            // if (list.foodImgVO) {
            //   list.foodImgVO = 'data:image/jpeg;base64,' + list.foodImgVO
            // }
            that.numberSum += list.number
            that.totalPrice += list.price
            // 直接把整个塞进去
            list.foodRemark = list.remark
            that.shopData.push(list)
          })
          this.hasShoppingData = !!this.shoppingCartData.length
        }
      })
    },
    // 关闭页面
    closeDialog(isRefresh) {
      // 保存购物车
      // saveShoppingCart(this.shopData).then(res => {})
      this.$emit('close', isRefresh)
    },
    // 关闭备注框
    // closeRemarkDialog() {
    //   this.remarkData.foodId = null
    //   this.remarkData.foodRemark = null
    //   this.remarkFormVisible = false
    // },
    // 保存备注
    // saveRemark(remarkData) {
    //   // 循环查找对应该id的shoppingCart，将备注存入该item
    //   this.shoppingCartData.forEach(function(list, index) {
    //     if (list.foodId === remarkData.foodId) {
    //       list.foodRemark = remarkData.foodRemark
    //     }
    //   })
    //   this.closeRemarkDialog()
    //   this.$notify.success('添加备注成功！')
    // },
    // 打开备注框
    // remarkDialog(item) {
    //   this.foodData = item
    //   this.remarkFormVisible = true
    //   this.remarkData.foodId = item.foodId
    //   this.remarkData.foodRemark = item.foodRemark
    //   this.remarkTitle = '为 ' + item.foodName + ' 添加备注'
    //   this.remarkFormVisible = true
    // },
    // 初始化界面
    initStoreAndFood() {
      getStoreInfo({ taskId: this.taskId }).then(res => {
        if (res.code === 200) {
          this.storeInfo = res.data
          // 处理图片
          // if (this.storeInfo.imgVO) {
          //   this.storeInfo.imgVO = 'data:image/jpeg;base64,' + this.storeInfo.imgVO
          // }
        }
      }).then(() => {
        this.foodParams.storeId = this.storeInfo.storeId
        list(this.foodParams).then(res => {
          if (res.code === 200) {
            this.foods = res.data
            this.foods.forEach(function(list, index) {
              // 为每一个菜品设置被选中属性
              list.isPress = false
              list.shoppingNumber = 0
              // if (list.imgVO) {
              //   list.imgVO = 'data:image/jpeg;base64,' + list.imgVO
              // }
            })

            setTimeout(() => { this.getShoppingCartData() }, 200)
          }
        })
      })
    },
    // 单独查询菜品
    pageList() {
      this.foodParams.storeId = this.storeInfo.storeId
      list(this.foodParams).then(res => {
        if (res.code === 200) {
          this.foods = res.data
          const that = this
          // 查询之后菜品的被选中属性和购物车数量会被清空，通过已点列表根据菜品id重新赋值
          this.foods.forEach(function(foodField) {
            that.shoppingCartData.forEach(function(shoppingField) {
              if (foodField.foodId === shoppingField.foodId) {
                // 如果有在购物车出现，肯定是被选中的
                foodField.shoppingNumber = shoppingField.number
                foodField.isPress = true
              }
            })
          })
        }
      })
    },
    // 删除菜品
    deleteFood(item) {
      const that = this
      this.shoppingCartData.forEach(function(list, index) {
        if (list.foodId === item.foodId) {
          that.numberSum--
          that.totalPrice -= item.price
          if (item.shoppingNumber === 1) {
            item.number = 0
            that.shoppingCartData.splice(index, 1)
            that.shopData.splice(index, 1)
            item.shoppingNumber = 0
            item.isPress = false
          } else {
            that.shoppingCartData[index].number--
            item.shoppingNumber--
          }
        }
      })
      if (!this.shoppingCartData.length) {
        this.hasShoppingData = false
      }
    },
    // 添加菜品
    selectFood(item) {
      this.hasShoppingData = true
      // 定义存在标记：循环到已经存在就设为true
      let flag = false
      // 在方法里面的this指向可能不是同一个,提前设置
      const that = this
      this.shoppingCartData.forEach(function(list, index) {
        if (list.foodId === item.foodId) {
          flag = true
          that.totalPrice += item.price
          // 说明之前已经添加，则更新计数器
          that.numberSum++
          list.number++
          item.shoppingNumber++
        }
      })
      if (!flag) {
        // 第一次添加，则显示并更新计数器
        that.numberSum++
        that.totalPrice += item.price
        item.singlePrice = item.price
        item.number = 1
        item.shoppingNumber = 1
        item.isPress = true
        // 直接将菜品数据放进下单传递的购物车数组中
        // 添加的时候新增一个foodRemark属性，不然会和菜品原有的remark混淆，页面会出现奇奇怪怪的问题
        item.foodRemark = null
        // item.foodImgVO = item.imgVO
        that.shopData.push(item)
        that.shoppingCartData.push(item)
      }
    },
    // 从购物车列表新增菜品
    selectFoodInShopping(shopItem) {
      // 购物车数据更新，下单列表更新和菜品数据的数字更新
      shopItem.number++
      this.totalPrice += shopItem.price
      this.numberSum++
      this.foods.forEach(function(list) {
        if (list.foodId === shopItem.foodId) {
          list.shoppingNumber++
        }
      })
    },
    // 从购物车列表删除菜品
    deleteFoodInShopping(shopItem) {
      // 如果数字为1，购物车删除这个菜品，否则做-1操作
      const that = this
      this.foods.forEach(function(list, index1) {
        if (list.foodId === shopItem.foodId) {
          that.numberSum--
          that.totalPrice -= shopItem.singlePrice
          if (shopItem.number === 1) {
            // 如果购物车列表剩下最后一个，遍历得到当前购物车菜品数据，从列表中删除该数据
            that.shoppingCartData.forEach(function(shopList, index2) {
              if (shopList.foodId === shopItem.foodId) {
                that.shoppingCartData.splice(index2, 1)
                that.shopData.splice(index2, 1)
              }
            })
            shopItem.number = 0
            list.shoppingNumber = 0
            list.isPress = false
          } else {
            shopItem.number--
            list.shoppingNumber--
          }
        }
      })
      if (!this.shoppingCartData.length) {
        this.hasShoppingData = false
      }
    },
    // 保存 (生成记录)
    confirmOrder() {
      this.$confirm('确定保存吗?', '保存确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (this.shopData > 0 || this.shopData !== undefined) {
            // 遍历加上任务码
            const that = this
            this.shopData.forEach(function(list) {
              list.taskId = that.taskId
            })
            // 保存购物车
            saveShoppingCart(this.shoppingCartData).then(() => {

            })
            // 保存订单
            saveOrder(this.shopData)
              .then(res => {
                if (res.code === 200) {
                  this.$message.success('保存成功')
                  this.closeDialog(true)
                } else {
                  this.$message.info('下单失败!')
                }
              })
              .catch(() => {
                this.$message.error('下单失败，请稍后再试！')
              })
          } else {
            this.$message.error('下单列表不能为空!')
            return false
          }
        })
    },
    // 清空购物车（前后端都要清除）
    resetFood() {
      this.$confirm('确定清空吗?', '清空确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetFood({ taskId: this.taskId })
          .then(res => {
            if (res.code === 500) {
              this.$message.info(res.message)
            } else {
              this.totalPrice = 0
              this.numberSum = 0
              this.shoppingCartData = []
              this.shopData = []
              this.foods.forEach(function(list, index) {
                list.isPress = false
                list.shoppingNumber = 0
              })
              this.hasShoppingData = false
            }
          })
      })
    }
  }
}
</script>

<style lang="scss">
  .dialogClass .el-dialog__header {
    height: 5%;
  }
  .dialogClass .el-dialog__body {
    height: 95%;
  }
  .main {
    width: 100%;
    height: 100%;
    padding: 10px;
    /*background: #B7E4F1;*/
  }
  .center {
    height: 100%;
    /*background: #C3CED1;*/
  }
  .right {
    height: 100%;
    /*background: #D2DDDB;*/
  }
  .center-top {
    height: 33px;
  }
  .center-bottom {
    margin-top: 2px;
    height: calc(100% - 33px);
    overflow: auto;
  }
  .right-top {
    height: 34px;
  }
  .right-center {
    padding: 5px;
    height: calc(100% - 34px - 85px);;
    overflow: auto;
  }
  .right-bottom {
    height: 85px;
  }

  .food-info {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 13px;
    .el-food-name {
      font-size: 18px;
      color: #666666;
    }
    .el-food-price {
      color: red;
      font-size: 20px;
      font-weight: bold;
    }
    .el-food-count {
      font-size: 11px;
      color: #5a5e66;
    }
    .food-count {
      color: #CE5639;
      font-size: 14px;
    }
  }
  .store-name {
    font-weight: bold;
    font-size: 28px;
  }
  .store-count {
    color: blue;
    font-size: 20px;
  }
  .search-input {
    width: 25%;
  }
  .input-number-component{
    font-size: 14px;
    .el-icon-minus {
      border: 1px solid #409EFF;
      border-radius: 4px;
      cursor: pointer;
      font-weight: bold;
      font-size: 13px;
    }
    .input-number {
      font-weight: bold;
      font-size: 13px;
    }
    .el-icon-plus {
      border-radius: 4px;
      background: #409EFF;
      cursor: pointer;
      color: white;
      font-weight: bold;
      font-size: 13px;
    }
  }
  .input-number-component-shopping {
    font-size: 16px;
    .el-icon-minus {
      border: 1px solid #409EFF;
      border-radius: 4px;
      cursor: pointer;
      font-weight: bold;
    }
    .input-number {
      font-weight: bold;
    }
    .el-icon-plus {
      border-radius: 4px;
      background: #409EFF;
      cursor: pointer;
      color: white;
      font-weight: bold;
    }
  }
  .shopping-price {
    color: red;
    font-size: 19px;
    font-weight: bold;
  }
  .shop-title {
    font-size: 25px;
    color: black;
    font-weight: bold;
  }
  .card-panel-col-food {
    margin-top: 10px;
    width: 350px;
    height: 160px;
  }
  .card-title-food {
    display: flex;
    align-items: center;
  }
  .right-format-food {
    height: 140px;
  }
  .image-food {
    height: 140px;
    width: 180px;
  }
  .title-span-food {
    font-size: 20px;
    font-weight: bold;
    margin-left: 10px;
  }
  .middle-food {
    margin-top: 30px;
    height: 50px;
  }
  .money {
    font-size: 20px;
    color: #66b1ff;
  }
  .count {
    font-size: 10px;
    color: gray;
    margin-left: 10px;
  }
  .div-descript-food {
    font-size: 10px;
    margin-left: 10px;
    margin-top: 10px;
    color: gray;
  }
  .card-panel-col-shopping {
    width: 100%;
    margin: 2px 0;
    padding: 5px;
    border-radius: 4px;
    border: 1px solid #ebeef5;
  }
  .card-title {
    display: flex;
    align-items: center;
    margin-left: 5px;
  }
  .right-format {
    width: 100%;
  }
  .image {
    height: 75px;
    width: 70px;
  }
  .title-span {
    font-size: 18px;
    font-weight: bold;
    margin-left: 5px;
  }
  .el-icon-remove-outline {
    border-radius: 35px;
  }
  .remark {
    border-radius: 35px;
  }
</style>
